package at.codebase.web.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.codebase.db.dao.EImageDao;
import at.codebase.db.entities.EImage;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;

public class ImageServService extends HttpServlet {
	
	private static ImagesService imagesService = ImagesServiceFactory.getImagesService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		try {
			long imageId = Long.parseLong(req.getParameter("id"));
			String imageHString = req.getParameter("h");
			String imageWString = req.getParameter("w");			
			
			EImage image = EImageDao.getImageById(new Long(imageId));
			
			if(image != null){
				
				BlobKey blobKey = new BlobKey(image.getImageBlobKey());			
				
				ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(blobKey);
				options.secureUrl(true);
				
				if(imageHString != null && imageWString != null){
					try{
						int imageHeight = Integer.parseInt(imageHString);
						int imageWidth  = Integer.parseInt(imageWString);
						
						options.imageSize(Math.max(imageHeight, imageWidth));
						
					}catch(Exception e){ }
				}else{
					options.imageSize(Math.max(image.getImageHeight(), image.getImageWidth()));
				}
				
				String servingUrl = imagesService.getServingUrl(options);
				resp.sendRedirect(servingUrl);
			
			}
		} catch (NumberFormatException e){
			
		}
		
	}
	
}
